package com.bdqn.controller;


import com.bdqn.entity.OmsOrder;
import com.bdqn.entity.UmsUser;
import com.bdqn.entity.util.Constants;
import com.bdqn.entity.util.RespBean;
import com.bdqn.entity.util.ResultEnum;
import com.bdqn.service.OmsOrderService;
import com.bdqn.service.UmsUserService;
import com.bdqn.util.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付记录表 前端控制器
 * </p>
 *
 * @author hunter
 * @since 2022-04-30
 */
@RestController
@RequestMapping("/oms/pay")
public class OmsPayLogController {
    private static Logger logger= LoggerFactory.getLogger(OmsPayLogController.class);
    @Autowired
    private UmsUserService umsUserService;
    @Autowired
    private OmsOrderService omsOrderService;
    @PostMapping("/aliPay/{orderNo}")
    public RespBean aliPay(@PathVariable String orderNo, HttpServletRequest request) throws Exception {
        System.out.println("接收的前端传来的订单编号为"+orderNo);
        String token = request.getHeader("token");
        UmsUser userByToken = umsUserService.getUserByToken(token);//获取到用户
        //通过用户查询到指定的订单 然后修改其状态信息
        OmsOrder orderByOderNo = omsOrderService.getOrderByOderNo(orderNo, userByToken.getId());
        // 校验订单信息
        checkOrder(orderByOderNo);
        //模拟支付
        orderByOderNo.setPayStatus(Constants.Order.PayStatus.SUCCESS);//支付成功
        orderByOderNo.setOrderStatus(Constants.Order.Status.WAIT_DELIVERY);//待发货
        orderByOderNo.setPayType(Constants.Order.PayWay.ONLINE);//在线支付
        orderByOderNo.setPayTime(new Date());//支付时间
        omsOrderService.updateById(orderByOderNo);

        Map<String,Object> map = new HashMap<>();
        map.put("payStatus", orderByOderNo.getPayStatus());
        return RespBean.ok("支付成功",map);
    }
    /**
     * 校验订单信息
     * @param omsOrder
     * @return
     */
    private void checkOrder(OmsOrder omsOrder) throws Exception {
        // 查询订单信息
        if (omsOrder == null) {
            logger.info("订单不存在");
            throw new BaseException(ResultEnum.ORDER_NOT_EXIST);
        }
        if (omsOrder.getOrderStatus().equals(Constants.Order.Status.TIMEOUT)) {
            logger.info("订单已过期");
          throw new BaseException(ResultEnum.ORDER_STATUS_TIMEOUT);
        }
        if(!omsOrder.getPayStatus().equals(Constants.Pay.PayStatus.WAIT)){
            logger.info("订单状态错误");
            throw new BaseException(ResultEnum.ORDER_STATUS_ERROR);
        }
    }
}
